package cn.kooki.app.duobao.ui.Activity.Goods;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Selection;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseActivity;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.Index.GoodsItem;
import cn.kooki.app.duobao.data.Bean.search.SearchResponse;
import cn.kooki.app.duobao.data.bus.AddSearchShopEvent;
import cn.kooki.app.duobao.data.bus.AddShopEvent;
import cn.kooki.app.duobao.data.bus.ChangePageEvent;
import cn.kooki.app.duobao.ui.Activity.Comm.RootAcitivity;
import cn.kooki.app.duobao.ui.Adapter.SearchResultAdapter;
import cn.kooki.app.duobao.ui.listener.AddShopCartCallBack;
import cn.kooki.app.duobao.ui.widget.CustomRelativeLayout;
import cn.kooki.app.duobao.util.manager.AppManager;
import cn.kooki.app.duobao.util.manager.CartObserver;
import cn.kooki.app.duobao.util.manager.ShopCartManager;
import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xionghao on 15/12/11.
 */
public class SearchActivity extends BaseActivity implements View.OnClickListener, CartObserver {
    @Bind(R.id.top_back_search)
    ImageButton topBackSearch;
    @Bind(R.id.search_edit_text)
    EditText searchEditText;
    @Bind(R.id.search_bar_wrapper)
    RelativeLayout searchBarWrapper;
    @Bind(R.id.search_keys_pg)
    TextView searchKeysPg;
    @Bind(R.id.search_keys_hw)
    TextView searchKeysHw;
    @Bind(R.id.search_keys_xm)
    TextView searchKeysXm;
    @Bind(R.id.search_keys_sj)
    TextView searchKeysSj;
    @Bind(R.id.search_keys_wrapper)
    LinearLayout searchKeysWrapper;
    @Bind(R.id.top_back)
    ImageButton topBack;
    @Bind(R.id.top_text)
    TextView topText;
    @Bind(R.id.top_cart)
    ImageButton topCart;
    @Bind(R.id.search_result_toolbar)
    RelativeLayout searchResultToolbar;
    @Bind(R.id.search_result_title_name)
    TextView searchResultTitleName;
    @Bind(R.id.search_result_title_add_all)
    Button searchResultTitleAddAll;
    @Bind(R.id.search_result_title)
    RelativeLayout searchResultTitle;
    @Bind(R.id.list_view)
    ListView listView;
    @Bind(R.id.loading_wrapper)
    CustomRelativeLayout loadingWrapper;
    @Bind(R.id.animation_wrapper)
    RelativeLayout animationWrapper;
    @Bind(R.id.animation_container)
    RelativeLayout animationContainer;
    @Bind(R.id.actionbar_badge)
    TextView actionbarBadge;


    private Animation animation;
    private SearchResultAdapter adapter;
    private String key;
    private long AnimationDuration = 600;
    private int statusBarHeight;

    @Override
    protected void setToolbar() {

        topBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                animationWrapper.setVisibility(View.GONE);
                searchKeysWrapper.setVisibility(View.VISIBLE);
            }
        });

        topBackSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        searchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_FLAG_NO_ENTER_ACTION) {
                    if (searchEditText.getText().length() > 0) {
                        dosearchkey();
                    }
                    hideSoftKeyBoard();
                    return true;
                } else {
                    return false;
                }


            }


        });

    }

    private int number = 0;
    private boolean isClean = false;
    private Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    //用来清除动画后留下的垃圾
                    try {
                        animationContainer.removeAllViews();
                        animationContainer.setVisibility(View.GONE);

                    } catch (Exception e) {

                    }
                    isClean = false;
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (statusBarHeight == 0) {
            Rect frame = new Rect();
            getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
            statusBarHeight = frame.top;
        }
    }

    private void doAnim(final AddSearchShopEvent event) {
        animationContainer.setVisibility(View.VISIBLE);

        final ImageView mAnimiImageView = new ImageView(this);
        mAnimiImageView.setLayoutParams(event.layoutParams);
        animationWrapper.addView(mAnimiImageView);
        mAnimiImageView.setImageDrawable(event.drawable);
        int fromx = event.loaction[0];
        int fromy = event.loaction[1];
        mAnimiImageView.setX(fromx);
        mAnimiImageView.setY(fromy - statusBarHeight);
        mAnimiImageView.setVisibility(View.VISIBLE);
        int[] end_location = new int[2];
        topCart.getLocationInWindow(end_location);
        int endX = end_location[0];
        int endY = end_location[1] - statusBarHeight;

        mAnimiImageView.animate().alpha(0.0f).setDuration(AnimationDuration).
                translationX(endX).scaleX(0.5f).scaleY(0.5f).translationY(endY).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                number--;
                mAnimiImageView.setVisibility(View.GONE);
                ShopCartManager.getInstance().addShopCart(event.item);

                if (number == 0) {
                    isClean = true;
                    myHandler.sendEmptyMessage(0);
                }
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                number++;
            }
        }).start();
    }

    private void dosearchkey() {
        refreshbadgeCount();

        animationWrapper.setVisibility(View.VISIBLE);
        searchKeysWrapper.setVisibility(View.GONE);
        loadingWrapper.showloading();
        key = searchEditText.getText().toString();
        Editable editable = searchEditText.getText();
        Selection.setSelection(editable, editable.length());
        dosearch();
    }

    private void refreshbadgeCount() {
        int size = ShopCartManager.getInstance().getCartsSize();
        if (size == 0) {
            actionbarBadge.setVisibility(View.GONE);
        } else {
            actionbarBadge.setText(size + "");
            actionbarBadge.setVisibility(View.VISIBLE);
        }
    }

    private void dosearch() {
        MainFactory.getApiInstance().search(key, new Callback<SearchResponse>() {
            @Override
            public void success(SearchResponse searchResponse, Response response) {
                loadingWrapper.hideloading();
                if (searchResponse.getData() != null) {
                    datas.clear();
                    datas.addAll(searchResponse.getData());
                    if (datas.size() == 0) {
                        String no_result = getResources().getString(R.string.search_no_result_tips);
                        String format = String.format(no_result, key);
                        loadingWrapper.setNoText(format);
                    } else {
                        loadingWrapper.hideNoText();
                        searchResultTitle.setVisibility(View.VISIBLE);
                        String title = getResources().getString(R.string.search_result_title);
                        String format = String.format(title, key, datas.size());
                        searchResultTitleName.setText(format);
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void failure(RetrofitError error) {
                loadingWrapper.hideloading();
            }
        });
    }


    @Override
    public void onBackPressed() {
        if (animationWrapper.getVisibility() == View.VISIBLE) {
            animationWrapper.setVisibility(View.GONE);
            searchKeysWrapper.setVisibility(View.VISIBLE);

        } else {
            super.onBackPressed();
        }
    }


    @Override
    protected void setLayoutContentView() {
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
    }

    private ArrayList<GoodsItem> datas = new ArrayList<>();


    @Override
    protected void afterView() {
        animationWrapper.setVisibility(View.GONE);
        adapter = new SearchResultAdapter(this, datas);
        adapter.setCartCallBack(new AddShopCartCallBack() {
            @Override
            public void excuteAnimi(AddSearchShopEvent shopEvent) {
                doAnim(shopEvent);
            }
        });
        listView.setAdapter(adapter);
        ShopCartManager.getInstance().changeObservable.registerObserver(this);
        searchKeysPg.setOnClickListener(this);
        searchKeysSj.setOnClickListener(this);
        searchKeysHw.setOnClickListener(this);
        searchKeysXm.setOnClickListener(this);
        searchResultTitleAddAll.setOnClickListener(this);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GoodsItem item = datas.get(position);
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("id", item.getId());
                params.put("qishu", item.getQishu());
                intent(GoodsDetailAcitvity.class, params);
            }
        });
        topCart.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ShopCartManager.getInstance().changeObservable.unregisterObserver(this);
    }

    @Override
    public void onClick(View v) {
        if (v == searchKeysHw) {
            searchEditText.setText(R.string.search_key_word_hua_wei);
            dosearchkey();
        }
        if (v == searchKeysPg) {
            searchEditText.setText(R.string.search_key_word_apple);
            dosearchkey();
        }
        if (v == searchKeysSj) {
            searchEditText.setText(R.string.search_key_word_phone);
            dosearchkey();
        }
        if (v == searchKeysXm) {
            searchEditText.setText(R.string.search_key_word_xiao_mi);
            dosearchkey();
        }
        if (v == topCart) {
            ChangePageEvent pageEvent = new ChangePageEvent();
            pageEvent.item = 3;
            EventBus.getDefault().post(pageEvent);
            AppManager.getAppManager().getTopWith(RootAcitivity.class);
        }
        if (v == searchResultTitleAddAll) {
            ShopCartManager.getInstance().addShopCarts(datas);
        }
    }

    @Override
    public void onChanged(int count) {

    }

    @Override
    public void onCheckedChange(int count, boolean isCancelEditing) {

    }

    @Override
    public void onCartsChange() {
        refreshbadgeCount();
    }
}
